<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="70%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item v-if="ruleForm.status == 'COMPLETED'" prop="fishOutTaskName">
                <span class="errorText">该任务已完成不可编辑</span>
            </el-form-item>
            <el-form-item label="任务名称" prop="fishOutTaskName">
                <el-input v-model="ruleForm.fishOutTaskName" clearable placeholder="请输入数量" class="w100p"></el-input>
            </el-form-item>
            <el-form-item label="码单号" prop="codeNumber">
                <el-input v-model="ruleForm.codeNumber" clearable placeholder="请输入数量" class="w100p"></el-input>
            </el-form-item>
            <el-form-item label="创建人" prop="staffId">
                <el-select v-model="ruleForm.staffId" filterable clearable class="w100p" @change="handleChangeStaff">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item label="创建日期" prop="buildDate">
                <el-date-picker v-model="ruleForm.buildDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
            <template>
                <el-form-item label="任务明细">
                    <el-table height="250" class="elTable" :data="ruleForm.detailList" style="width: 100%" border>
                        <el-table-column label="出鱼类型">
                            <template slot-scope="scope">
                                <el-form-item :prop="`detailList[${scope.$index}][fishType]`" :rules="rules.fishType">
                                    <el-select placeholder="选择出鱼类型" v-model="scope.row.fishType" filterable clearable
                                        class="w100p">
                                        <el-option label="活鱼" value="LIVE_FISH" />
                                        <el-option label="次鱼" value="SECONDARY_FISH" />
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="出鱼品种">
                            <template slot-scope="scope">
                                <el-form-item :prop="`detailList[${scope.$index}][fishVarietyId]`"
                                    :rules="rules.fishVarietyId">
                                    <el-select v-model="scope.row.fishVarietyId" filterable clearable class="w100p"
                                        placeholder="选择出鱼品种"
                                        @change="() => { handleChangeFishVariety(scope.row.fishVarietyId, scope.$index) }">
                                        <el-option v-for="item, index in fishVarietyList" :key="index"
                                            :label="item.varietyName" :value="item.fishVarietyId" />
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="出鱼规格">
                            <template slot-scope="scope">
                                <el-form-item :prop="`detailList[${scope.$index}][specificationId]`"
                                    :rules="rules.specificationId">
                                    <el-select filterable clearable v-model="scope.row.specificationId"
                                        placeholder="选择出鱼规格" class="w100p">
                                        <el-option v-if="scope.row.fishVarietyId == item.fishVarietyId"
                                            v-for="item, index in specificationList" :key="index"
                                            :label="item.specificationName" :value="item.specificationId" />
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="数量">
                            <template slot-scope="scope">
                                <el-form-item :prop="`detailList[${scope.$index}][num]`" :rules="rules.num">
                                    <el-input v-model="scope.row.num" clearable placeholder="请输入数量" type="number"
                                        class="w100p">
                                        <template slot="append">尾</template>
                                    </el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="重量">
                            <template slot-scope="scope">
                                <el-form-item :prop="`detailList[${scope.$index}][weight]`" :rules="rules.weight">
                                    <el-input v-model="scope.row.weight" placeholder="请输入重量" clearable type="number"
                                        class="w100p">
                                        <template slot="append">斤</template>
                                    </el-input>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" v-if="ruleForm.status !== 'COMPLETED'">
                            <template slot-scope="scope">
                                <span v-show="scope.$index + 1 == ruleForm.detailList.length" class="icon successText"
                                    @click.stop="addMaterial()">添加</span>
                                <span v-show="ruleForm.detailList.length > 1" class="icon errorText"
                                    @click.stop="delMaterial(scope.$index)">删除</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </template>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <SaveDraftBox ref="saveDraft" v-if="addEditFlag == 'add' && dialogVisible" :formData="ruleForm"
                @pushData="pushData">
            </SaveDraftBox>
            <el-button type="primary" @click="submitForm" v-show="ruleForm.status !== 'COMPLETED'">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import fishHarvestingTaskManagement from '@/api/production-management/fish-harvesting-task-management.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        fishPondList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        fishVarietyList: {
            type: Array,
            default: () => {
                return []
            }
        },
        specificationList: {
            type: Array,
            default: () => {
                return []
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的数'));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                fishOutTaskName: [
                    { required: true, message: '请输入任务名称', trigger: 'change' }
                ],
                fishType: [
                    { required: true, message: '请选择任务类型', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                weight: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                buildDate: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                fishVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                specificationId: [
                    { required: true, message: '请选择品种规格', trigger: 'change' }
                ]
            }
        }
    },
    computed: {},
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = fishHarvestingTaskManagement.add
                this.addEditName = '添加';
                this.getInitRulFormData();
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = fishHarvestingTaskManagement.edit
                this.addEditName = '编辑';
                this.detailQueryByCondition(this.data.fishOutTaskId)
            }
        },
        pushData(data) {
            this.ruleForm = { ...data };
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            })
        },
        async detailQueryByCondition(fishOutTaskId) {
            let detailList = [{
                "fishType": "",
                "fishVarietyId": "",
                "fishVarietyName": "",
                "num": "",
                "specName": "",
                "specificationId": "",
                "weight": ""
            }]
            fishHarvestingTaskManagement.detailQueryByCondition({ fishOutTaskId }).then(res => {
                let data = res.data;
                if (data.length == 0) {
                    this.$set(this.ruleForm, 'detailList', detailList);
                } else {
                    this.$set(this.ruleForm, 'detailList', data);
                }
            }).catch(err => {
                this.$set(this.ruleForm, 'detailList', detailList);
            });
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let id = sessionStorage.getItem('staffId') || null;
            let detailList = [{
                "fishType": "",
                "fishVarietyId": "",
                "fishVarietyName": "",
                "num": "",
                "specName": "",
                "specificationId": "",
                "weight": ""
            }]
            let params = {
                staffId: id == 'null' ? '' : Number(id),
                buildDate: this.$formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
                detailList: detailList
            }
            this.$set(this, 'ruleForm', params);
        },
        //添加明细
        addMaterial() {
            let length = this.ruleForm.detailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.detailList, length, {
                    "fishType": "",
                    "fishVarietyId": "",
                    "fishVarietyName": "",
                    "num": "",
                    "specName": "",
                    "specificationId": "",
                    "weight": ""
                })
                this.$nextTick(() => {
                    this.$refs['ruleForm'].clearValidate()
                })
            }
        },
        //删除明细
        delMaterial(index) {
            let list = this.ruleForm.detailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'detailList', list);
            this.$nextTick(() => {
                this.$refs['ruleForm'].clearValidate()
            })
        },
        //选择鱼塘时提示用户是否存在该关联批次
        handleChangeFishPond(id) {
            let rut = this.batchList.find(item => item.fishPondId == id);
            let batchId = rut?.batchId
            this.$set(this.ruleForm, 'batchId', batchId || '');
            !rut && this.$message.warning('该鱼塘暂无批次!');
        },
        //选择品种时提示用户是否存在该品种规格
        handleChangeFishVariety(id, index) {
            let rut = this.specificationList.find(item => item.fishVarietyId == id);
            let specificationId = rut?.specificationId
            this.ruleForm.detailList[index].specificationId = specificationId || '';
            !rut && this.$message.warning('该鱼种暂未配置规格!');
            this.$nextTick(() => {
                this.$refs['ruleForm'].clearValidate()
            })
        },
        //获取人姓名
        handleChangeStaff(id) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName
            this.$set(this.ruleForm, 'staffName', staffName || '');
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.message || msg)
                        res.success && this.cancel();
                        //提交数据时删除保存的记录
                        res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.elTable {
    margin-bottom: 15px;

    ::v-deep .el-form-item__content {
        margin-left: 0 !important;
    }

    .el-form-item {
        margin-bottom: 0;
        padding: 15px 0;
    }
}

.icon {
    padding: 0 10px;
}
</style>